package com.bjfu.gmms.servlet;

import com.bjfu.gmms.MyBatisUtil;
import com.bjfu.gmms.mapper.MentorInfoMapper;
import com.bjfu.gmms.model.Mentor2;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/updateMentorInfo")
public class UpdateMentorInfo extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Integer mentorId = Integer.parseInt(request.getParameter("mentorId"));
        String admissionQualification = request.getParameter("admissionQualification");
        Integer quota = Integer.parseInt(request.getParameter("quota"));

        String message;  // 用于存放操作结果信息
        boolean success = false;  // 标识操作是否成功

        try (SqlSession sqlSession = MyBatisUtil.getSqlSession("development")) {
            MentorInfoMapper mapper = sqlSession.getMapper(MentorInfoMapper.class);
            Mentor2 mentor = mapper.selectMentorInfoById(mentorId);

            if (mentor != null) {
                // 更新导师信息
                mentor.setAdmissionQualification(admissionQualification);
                mentor.setQuota(quota);
                mentor.setMentorId(mentorId);
                mapper.updateMentorInfo(mentor);

                // 提交事务
                sqlSession.commit();
                success = true;
                message = "更新成功！";
            } else {
                message = "未找到导师信息！";
            }
        } catch (Exception e) {
            e.printStackTrace();
            message = "更新失败，发生异常！";
        }

        // 返回结果到前端
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write("<script type=\"text/javascript\">");
        if (success) {
            response.getWriter().write("alert('" + message + "');");
            response.getWriter().write("history.back();"); // 跳转到成功页面
        } else {
            response.getWriter().write("alert('" + message + "');");
            response.getWriter().write("history.back();"); // 返回上一个页面
        }
        response.getWriter().write("</script>");
    }
}